<?php

namespace App\Http\Controllers\Import;

use App\Http\Controllers\Admin\CommonController;
use App\Http\Controllers\Controller;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityArea;
use App\Models\AnswerActivityProblem;
use App\Models\AnswerActivityProblemAnswer;
use App\Models\AnswerActivityUnit;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * excel导入功能
 */
class AnswerActivityProblemImport extends Controller
{
    public $model = null;
    public $request = null;
    public $commonObj = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->model = new AnswerActivityProblem();
        $this->commonObj = new CommonController();
    }

    /**
     * 活动题库导入
     * @param file  excel 文件名
     * @param act_id  活动id
     * @param is_update  遇到重复数据，是否覆盖更新  1 更新  2 不更新 （默认2）  
     */
    public function index()
    {
        set_time_limit(500);
        ini_set('memory_limit', '1024M');
        
        $is_update = $this->request->input('is_update', 2);
        $act_id = $this->request->input('act_id', '');

        $activityModel = new AnswerActivity();
        $node = $activityModel->where('id', $act_id)->where('is_del', 1)->value('node');

        DB::beginTransaction();
        try {
            //图片保存目录
            $img_dir = public_path('uploads') . '/problem/' . date('Y-m-d') . '/';
            if (!is_dir($img_dir)) {
                @mkdir($img_dir, 0777, true);
            }

            $importObj = new Import();
            $data = $importObj->getData($this->request, 'file', 'activity_problem_import', $img_dir);

            $checkTemplate = $this->checkTemplate($data, $node);
            if ($checkTemplate !== true) {
                return $this->commonObj->returnApi(202, '模板有误，请重新下载模板');
            }

            array_shift($data); //去掉第一个元素，数据中没删除头部

            // $success = 0;//成功个数
            $error = 0; //失败个数
            $error_msg = ''; //失败原因
            $activityUnitModel = new AnswerActivityUnit();

            foreach ($data as $key => $val) {
                $serial = $val[0];
                if ($node == 1) {
                    $title = $val[1];
                    $img = $val[2];
                    $type = $val[3];
                    $success_answer = $val[4];
                    $answer1 = $val[5];
                    $answer2 = $val[6];
                    $answer3 = $val[7];
                    $answer4 = $val[8];
                    $answer5 = $val[9];
                    $is_show_analysis = $val[10];
                    $analysis = $val[11];
                } else {
                    $unit_name = $val[1];
                    $title = $val[2];
                    $img = $val[3];
                    $type = $val[4];
                    $success_answer = $val[5];
                    $answer1 = $val[6];
                    $answer2 = $val[7];
                    $answer3 = $val[8];
                    $answer4 = $val[9];
                    $answer5 = $val[10];
                    $is_show_analysis = $val[11];
                    $analysis = $val[12];

                    //判断区域在系统是否存在 
                    if (!empty($unit_name)) {
                        $unit_id = $activityUnitModel->where('name', $unit_name)->where('act_id', $act_id)->where('is_del', 1)->value('id');
                        if (empty($unit_id)) {
                            $error++;
                            $error_msg .= '[序号：“' . $serial . '” 的单位名称在系统不存在]';
                            continue;
                        }
                    } else {
                        $unit_id = 0;
                    }
                }
                $img = substr($img, 0, 1) == '/' ? substr($img, 1, strlen($img)) : $img; //去掉第一个 / 斜线

                if (empty($title)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '” 的标题不能为空]';
                    continue;
                }
                if (empty($success_answer)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '” 的正确答案不能为空]';
                    continue;
                }

                $type = $this->getType($type);

                if (empty($type)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”题目类型错误]';
                    continue;
                }

                $answer_number = 0;
                if ($answer1) $answer_number++;
                if ($answer2) $answer_number++;
                if ($answer3) $answer_number++;
                if ($answer4) $answer_number++;
                if ($answer5) $answer_number++;

                if ($type == 1 && ($answer_number < 2)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”的选择题的答案最少2个！]';
                    continue;
                }
                if ($type == 2 && $answer_number != 1) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”的填空题的答案只能存在一个！]';
                    continue;
                }

                //判断名称是否存在
                $condition[] = ['act_id', '=', $act_id];
                if ($node != 1) {
                    $condition[] = ['unit_id', '=', $unit_id];
                }

                $is_exists = $this->model->nameIsExists($title, 'title', null, 1, $condition);
                if (empty($is_exists)) {
                    $activityProblemModel = new AnswerActivityProblem();
                    $activityProblemModel->add([
                        'act_id' => $act_id,
                        'unit_id' => $unit_id ?? 0,
                        'img' => $img,
                        'title' => $title,
                        'type' => $type,
                        'analysis' => $analysis,
                        'is_show_analysis' => $is_show_analysis == '是' ? 1 : 2,
                    ]); //覆盖更新数据

                    list($answer, $success_answer_number) = $this->setAnswerData($answer1, $answer2, $answer3, $answer4, $answer5, $success_answer, $activityProblemModel->id);

                    if (empty($success_answer_number)) {
                        $error++;
                        $error_msg = '[序号：“' . $serial . '” 的正确答案与选项不匹配，请检查]';
                        throw new Exception($error_msg); //存在特殊情况，答案错误，需要回滚
                    }
                    if ($success_answer_number != 1) {
                        $error++;
                        $error_msg = '[序号：“' . $serial . '” 的正确答案与选项存在多个相同的情况，请检查]';
                        throw new Exception($error_msg); //存在特殊情况，答案错误，需要回滚
                    }

                    //添加答案
                    $activityProblemAnswerModel = new AnswerActivityProblemAnswer();
                    $answer_id = $activityProblemAnswerModel->add($answer, $activityProblemModel->id, $type);

                    $activityProblemModel->answer_id = $answer_id; //修改正确答案id
                    $activityProblemModel->save();
                } else {
                    if ($is_update == 1) {
                        list($answer, $success_answer_number) = $this->setAnswerData($answer1, $answer2, $answer3, $answer4, $answer5, $success_answer, $is_exists->id);

                        if (empty($success_answer_number)) {
                            $error++;
                            $error_msg = '[序号：“' . $serial . '” 的正确答案与选项无匹配项，请检查]';
                            throw new Exception($error_msg); //存在特殊情况，答案错误，需要回滚
                        }
                        if ($success_answer_number != 1) {
                            $error++;
                            $error_msg = '[序号：“' . $serial . '” 的正确答案与选项存在多个相同的情况，请检查]';
                            throw new Exception($error_msg); //存在特殊情况，答案错误，需要回滚
                        }

                        $this->model->change([
                            'id' => $is_exists->id,
                            'unit_id' => $unit_id ?? 0,
                            'img' => $img,
                            'title' => $title,
                            'type' => $type,
                            'analysis' => $analysis,
                            'is_show_analysis' => $is_show_analysis == '是' ? 1 : 2,
                        ]); //覆盖更新数据

                        //删除掉之前的图片
                        if ($img && $is_exists->img) {
                            $this->commonObj->deleteFile($is_exists->img);
                        }

                        //添加答案
                        $activityProblemAnswerModel = new AnswerActivityProblemAnswer();
                        $answer_id = $activityProblemAnswerModel->importChange($answer, $is_exists->id, $type);

                        $is_exists->answer_id = $answer_id; //修改正确答案id
                        $is_exists->save();
                    } else {
                        $error++;
                        $error_msg .= '[序号：“' . $serial . '” 题目名称:' . $title . ' 已存在,不允许重复添加]';
                        continue;
                    }
                }
            }

            DB::commit();
            $return_msg = "导入成功，" . '错误: ' . $error . ' 个';
            if ($error) $return_msg .= '错误原因:' . $error_msg;

            return $this->commonObj->returnApi(200, $return_msg, true);
        } catch (\Exception $e) {
            // echo $e->getMessage();
            // echo $e->getFile();
            // echo $e->getLine();
            DB::rollBack();
            return $this->commonObj->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 检查模板是否正确 (必须与模板对应)
     *
     * @param [type] $type
     * @return void
     */
    public function checkTemplate($data, $node)
    {
        if ($node == 1) {
            if (
                $data[0][0] != '序号' ||
                $data[0][1] != '题目' ||
                $data[0][2] != '图片' ||
                $data[0][3] != '题目类型（选择、填空二选一）' ||
                $data[0][4] != '正确答题（必须与选项内容一致）' ||
                $data[0][5] != '答题1（若是填空题，答案1就等于正确答案）' ||
                $data[0][6] != '答题2' ||
                $data[0][11] != '解析'

            ) {
                return false;
            }
        } else {
            if (
                $data[0][0] != '序号' ||
                $data[0][1] != '所属单位' ||
                $data[0][2] != '题目' ||
                $data[0][3] != '图片' ||
                $data[0][4] != '题目类型（选择、填空二选一）' ||
                $data[0][5] != '正确答题（必须与选项内容一致）' ||
                $data[0][6] != '答题1（若是填空题，答案1就等于正确答案）' ||
                $data[0][7] != '答题2' ||
                $data[0][12] != '解析'

            ) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取type 数据
     *
     * @param [type] $data
     * @return void
     */
    public function getType($type)
    {
        $type = mb_substr($type, 0, 2);

        if ($type == '选择' || $type == '选择题') {
            return 1;
        } elseif ($type == '填空' || $type == '填空题') {
            return 2;
        } else {
            return false;
        }
    }

    /**
     * 组装答案数据
     * @param $data 数组数据
     */
    public function setAnswerData($answer1, $answer2, $answer3, $answer4, $answer5, $success_answer, $pro_id)
    {
        $answer = [];
        $success_answer_number = 0;
        $a = 0;
        for ($i = 1; $i <= 5; $i++) {
            if (${'answer' . $i}) {
                $answer[$a]['content'] = ${'answer' . $i};
                $answer[$a]['pro_id'] = $pro_id;
                if (${'answer' . $i} == $success_answer) {
                    $answer[$a]['status'] = 1;
                    $success_answer_number++;
                } else {
                    $answer[$a]['status'] = 2;
                }
            }
            $a++;
        }

        return [$answer, $success_answer_number];
    }
}
